//
//  JCComposeView.swift
//  SinaWeibo_18
//
//  Created by apple on 15/10/23.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
import pop

class JCComposeView: UIView {

    var targetViewController: UIViewController?
    //按钮数组
    private lazy var composeButtons: [JCComposeButton] = [JCComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //当前控件的大小
        self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight)
        //添加背景图片
        let imageView = UIImageView(image: screenImage().applyLightEffect())
        imageView.size = size
        addSubview(imageView)
        //添加button
        addMenuButton()
        //添加顶部品牌的图标
        addSubview(sloganImage)
    }
    //显示当前控件到控制器
    func show(target target:UIViewController){
        //把当前控件添加到屏幕上
        //        let window = UIApplication.sharedApplication().keyWindow
        //        window?.addSubview(self)
        
        target.view.addSubview(self)
        self.targetViewController = target
        //执行动画
        for(index,value) in composeButtons.enumerate(){
            didAnim(index, value: value, centerY: value.centerY - 400)
        }
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        dismiss()
    }
    //移除整个view控件
    private func dismiss(){
        //反转遍历
        for (index,value) in composeButtons.reverse().enumerate(){
            didAnim(index, value: value, centerY: value.centerY+400)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
        
        
    }
    
    private func didAnim(index: Int, value: UIButton, centerY: CGFloat){
        //添加动画
       
            //初始弹性动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            anim.toValue = NSValue(CGPoint: CGPointMake(value.centerX, centerY))
            //弹性幅度
            anim.springBounciness = 10
            //速度
            anim.springSpeed = 10
            //动画开始时间
            anim.beginTime = CACurrentMediaTime() + Double(index)*0.025
            //给当前遍历的控件添加动画
            value.pop_addAnimation(anim, forKey: nil)
        

    }
    //获取背景图片(屏幕截图)
    private func screenImage() -> UIImage{
        let window = UIApplication.sharedApplication().keyWindow
        //截图
        //开启图形上下文(参数2(opaque):是否透明)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(ScreenWidth, ScreenHeight), false, 1)
        //画到图形上下文
        window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false)
        //取出图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //磨砂
//        image = image.applyLightEffect()
        //关闭
        UIGraphicsEndImageContext()
        return image
        
        //存储文件
        //            let imageData = UIImagePNGRepresentation(image)
        //            imageData?.writeToFile("", atomically: true)

    }
    //按钮
    private func addMenuButton(){
        //读取plist文件
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let composeButtonInfos = NSArray(contentsOfFile: path!)
        let childButtonMargin = (ScreenWidth - 3 * COMPOSE_BUTTONW)/4
        for i in 0..<composeButtonInfos!.count{
            let button = JCComposeButton()
            //添加button点击动画
            button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //取出当前按钮显示的信息
            let info = composeButtonInfos![i] as! [String: AnyObject]
            button.setImage(UIImage(named: (info["icon"] as! String)), forState: UIControlState.Normal)
            button.setTitle((info["title"] as! String), forState: UIControlState.Normal)
            
            let col = i % 3
            let row = i / 3
            button.x = CGFloat(col+1)*childButtonMargin + CGFloat(col)*COMPOSE_BUTTONW
            button.y = CGFloat(row)*COMPOSE_BUTTONH + ScreenHeight
            addSubview(button)
            composeButtons.append(button)
        }
    }
    //button 点击事件  点击放大动画
    @objc private func composeButtonClick(button: JCComposeButton){
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.composeButtons{
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.25, 0.25)
                }
                value.alpha = 0.0
            }
            }) { (finish) -> Void in
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    for value in self.composeButtons{
//                        value.transform = CGAffineTransformIdentity
//                        value.alpha = 1
//                    }
//                })
                //弹出新控制器
//                let ctrl = JCComposeViewController()
                let nav = UINavigationController(rootViewController: JCComposeViewController())
                self.targetViewController?.presentViewController(nav, animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
        }
    }
    //最上方品牌图标
    private lazy var sloganImage: UIImageView = {
            let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
        imageView.centerX = self.centerX
        imageView.y = 100
        
        return imageView
        }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
